import React, { cloneElement, useRef } from 'react';

function ReadOnly({ onChange: propOnChange, component: Comp, children, readOnly, ...rest }) {
  const voidChange = useRef(() => {}).current;
  const onChange = readOnly ? voidChange : propOnChange;
  return Comp ? (
    <Comp onChange={onChange} {...rest}>
      {children}
    </Comp>
  ) : (
    cloneElement(children, { onChange, ...rest })
  );
}

export default ReadOnly;
